package it.amicosmanettone.finance.stocky;

import java.util.ArrayList;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.text.InputType;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import it.amicosmanettone.finance.stocky.adapter.ListAdapterSearchStock;
import it.amicosmanettone.finance.stocky.archive.ArchiveManager;
import it.amicosmanettone.finance.stocky.bean.SingleStockBean;
import it.amicosmanettone.finance.stocky.util.ErrorCode;
import it.amicosmanettone.finance.stocky.util.FinanceUtil;

public class SearchStockActivity extends Activity {

	static ArrayList<SingleStockBean> singleStockBeanList = null;

	Button buttonSearch;
	TextView noStockSearch;

	String nameOfPortfolio;
	int POSITION;

	String textError;
	String textOkBox;
	ListView listStocks = null;

	boolean NETWORK;

	private static ListAdapterSearchStock adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_stock);
		
		this.NETWORK = isNetworkAvailable();
		if(NETWORK == false){
			
			errorConnection();
			
		}

		Bundle extras = getIntent().getExtras();

		this.nameOfPortfolio = extras.getString("nameOfPortfolio");
		this.POSITION = extras.getInt("POSITION");

		this.buttonSearch = (Button) findViewById(R.id.buttonSearch);
		this.noStockSearch = (TextView) findViewById(R.id.textNoStocksSearch);
		noStockSearch.setText("");
		
		final ListView listStocks = (ListView) this
				.findViewById(R.id.listOfStock);
		final EditText nameOfStockToSearchEdit = (EditText) findViewById(R.id.nameOfStockToSearch);

		Typeface robotoThin = Typeface.createFromAsset(getAssets(),
				"Roboto-Thin.ttf");
		nameOfStockToSearchEdit.setTypeface(robotoThin);
		nameOfStockToSearchEdit.refreshDrawableState();

		final ProgressDialog mProgressDialog = new ProgressDialog(this);
		String textDialogSendMail = getText(R.string.textProgressLoad)
				.toString();

		mProgressDialog.setMessage(textDialogSendMail);
		mProgressDialog.setCancelable(false);

		this.buttonSearch.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				
				noStockSearch.setText("");
				

				String nameOfStock = nameOfStockToSearchEdit.getEditableText()
						.toString();
				if (!nameOfStock.isEmpty()){
					if(nameOfStock.length() > 35){
						errorBox("ERROR_LENGHT");
					}else{
					
					NETWORK = isNetworkAvailable();
					if(NETWORK == false){
						
						errorConnection();
						
					}

					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							
							Log.e("PROGRESS","MOSTRO");

							mProgressDialog.show();

						}
					});
					
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(
							nameOfStockToSearchEdit.getWindowToken(), 0);
	
					singleStockBeanList = FinanceUtil
							.searchStocksOnline(nameOfStock);
					String noStockSearchString = getText(R.string.addStockNoStock).toString();
					
					if(singleStockBeanList.size() <= 0){
						
						noStockSearch.setText(noStockSearchString);
						
					}

					adapter = new ListAdapterSearchStock(
							getApplicationContext(), R.layout.row_stock_search,
							singleStockBeanList);

					listStocks.setAdapter(adapter);

					
					
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							
							Log.e("PROGRESS","LEVO");

							mProgressDialog.dismiss();

						}
					});
					
					

				}
				}// End if !empty
				else if (nameOfStock.isEmpty()) {

					errorBox("NAME_STOCK_EMPTY");

				}// End else if empty
			}// End on click
		});// End onClickButton

		listStocks.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// selected item

				String nameOfStock = singleStockBeanList.get(position)
						.getStockName();
				String symbolOfStock = singleStockBeanList.get(position)
						.getStockSymbol();
				String marketOfStock = singleStockBeanList.get(position)
						.getStockMarket();
				String currencyOfStock = singleStockBeanList.get(position)
						.getStockCurrency();

				SingleStockBean newStock = new SingleStockBean(symbolOfStock,
						nameOfStock, marketOfStock, currencyOfStock);

				insertStockIntoPortfolio(newStock);

			}

		});// End list On Item Click

		setupActionBar();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void errorBox(String ACTION) {

		if (ACTION.equals("NAME_STOCK_EMPTY")) {
			
			this.textError = getText(R.string.textErrorBox).toString();
			
		} else if (ACTION.equals("ERR_EXIST")) {
			
			this.textError = getText(R.string.addStockErrorOnSearch).toString();
			
		} else if (ACTION.equals("ERROR_PREMIUM")) {
			
			this.textError = getText(R.string.addStockErrorOnSearchNoPremium).toString();
			
		} else if (ACTION.equals("ERROR_NUM_EMPTY")) {
			
			this.textError = getText(R.string.addStockErrorEmptyNum).toString();
			
		} else if(ACTION.equals("ERROR_LENGHT")){
			
			this.textError = getText(R.string.addStockErrorLength).toString();
			
		} else if(ACTION.equals("ERROR_NUM_LENGHT")){
			
			this.textError = getText(R.string.addStockErrorNumLength).toString();
			
		}

		String OKButton = getText(R.string.buttonErrorBoxOK).toString();

		new AlertDialog.Builder(this)
				.setMessage(textError)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						}).show();

	}// End errorBox

	public void insertStockIntoPortfolio(final SingleStockBean newStock) {

		String title = getText(R.string.addStockTitle).toString();
		String text = getText(R.string.addStockText).toString();
		String buttonY = getText(R.string.addStockYES).toString();
		String buttonN = getText(R.string.addStockNO).toString();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title);
		alert.setMessage(text);
		alert.setCancelable(false);

		final EditText numberStock = new EditText(this);
		numberStock.setInputType(InputType.TYPE_CLASS_NUMBER);
		alert.setView(numberStock);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int whichButton) {

				String numberOfStockString = numberStock.getEditableText()
						.toString();

				if (!numberOfStockString.isEmpty()) {

					int numberOfStock = Integer.valueOf(numberOfStockString)
							.intValue();
					
					if(numberOfStock > 999999){
						errorBox("ERROR_NUM_LENGTH");
					}else if (numberOfStock <= 0) {
						errorBox("ERROR_NUM_EMPTY");
					} else if (numberOfStock > 0) {
						newStock.setStockNumbers(numberOfStock);
						String isAdded = FinanceUtil.getAllPortfolio()
								.get(POSITION).addNewStock(newStock);
						if (isAdded.equals(ErrorCode.NO_ERROR)) {
							String STORE = ArchiveManager
									.storeAllPortfolios(getApplicationContext());
							if (STORE.equals(ErrorCode.NO_ERROR)) {
								Log.v("SALVO STOCK", "Mostro OK");
								okBox("ADD_STOCK_OK");
							} else {
								Log.v("SALVO STOCK", "ERRORE");
								errorBox("ERROR_GENERAL");
							}

						} else if (isAdded.equals(ErrorCode.ERR_EXIST)) {
							errorBox("ERR_EXIST");
						} else if (isAdded.equals(ErrorCode.ERR_NO_PREMIUM)) {
							errorBox("ERROR_PREMIUM");
						}
					}// End else if >0
				}// End if String !isEmpty()
				else if (numberOfStockString.isEmpty()) {
					errorBox("ERROR_NUM_EMPTY");
				}
			} // End of onClick
		}); // End of alert.setPositiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of alert.setNegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}// End insertStockIntoPortfolio

	public void okBox(String ACTION) {

		if (ACTION.equals("ADD_STOCK_OK")) {

			this.textOkBox = getText(R.string.addStockOKText).toString();

		}

		final String OKButton = getText(R.string.addStockOKButton).toString();
		final String namePortfolio = this.nameOfPortfolio;

		new AlertDialog.Builder(this)
				.setMessage(textOkBox)

				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {
								 
							Intent returnToPortfolio = new	Intent(getApplicationContext(),	StockPortfolioActivity.class);
							returnToPortfolio.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
							returnToPortfolio.putExtra("nameOfPortfolio", namePortfolio);
							returnToPortfolio.putExtra("POSITION", POSITION);
							startActivity(returnToPortfolio);
								 

							}
						}).show();

	}// End okBox

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}// End isNetworkAvailable

	private void errorConnection() {

		this.textError = getText(R.string.addStockNoConnection).toString();

		String OKButton = getText(R.string.buttonErrorBoxOK).toString();

		new AlertDialog.Builder(this)
				.setMessage(textError)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

								finish();

							}
						}).show();

	}// End errorConnection

}
